import threading
import time
from .ws import ws_send
from .LCD import set_message

Refrigeration = 0  #制热
Heating = 1  #制冷
StopWind = 2  #停止送风
HighSpeed = 2
MidSpeed = 1
LowSpeed = 0

# 设置夏天常温30，冬天常温15
SummerTemp = 30
WinterTemp = 15

personInfo = {
    "ID": 0,
    "NationalCard": "0000",
    "Room": "000",
    "CustomerName": "日天",
    "Done": "false",
    "Cost": 0
}
config = {
    "id": None,
    "room": None,
    "masterMode": 0,  #主机工作模式
    "clientMode": StopWind,  #从机当前工作模式
    "temp": 0,  #主机工作温度
    "updateInterval": 1000 * 1,  #从机状态上报间隔，默认  1s 上传一次状态
}
roomState = {
    "currentTemp": 0,  #从机当前温度
    "tarTemp": 0,  #从机目标温度
    "speed": 1,  #风速
    "cost": 0,  #从机消耗的金钱总数
}
#状态上报的定时器 在python中直接使用线程代替，对应的bool值帮助在需要的时候杀死线程
handler = {
    "reportState": None,
    "reportState_run": True,
    "activity": None,
    "activity_run": True,
}
haveWind = False  #主机是否正在向该从机送风
init = False
normalExit = False  #标志该主机退出是否是因为用户按了退出键，还是因为主机宕了


def state_string():
    mode = ("cold", "hot")
    speed = ("low", "mid", "high")
    return "{}    {}\n{} c    {}".format(mode[config['masterMode']],
                                         speed[roomState['speed']],
                                         str(round(roomState['tarTemp'], 1)),
                                         str(round(roomState['cost'], 1)))


def reportState_thread():
    while handler["reportState_run"]:
        ws_send({
            "event_id": 7,
            "data": {
                "cur_temp": roomState["currentTemp"],
                "tar_temp": roomState["tarTemp"],
                "mode": config["clientMode"],
                "speed": roomState["speed"],
            }
        })
        time.sleep(config["updateInterval"] / 1000)
    handler["reportState_run"] = True


def reportState():
    handler["reportState"] = threading.Thread(target=reportState_thread,
                                              name='ReportStateThread')
    handler["reportState"].start()


def reportStateNow():
    ws_send({
        "event_id": 7,
        "data": {
            "cur_temp": roomState["currentTemp"],
            "tar_temp": roomState["tarTemp"],
            "mode": config["clientMode"],
            "speed": roomState["speed"],
        }
    })


def activity_thread():
    global haveWind
    while handler["activity_run"]:
        #确认当前平衡的温度
        aimTemp = WinterTemp if config["masterMode"] == Heating else SummerTemp
        # 若当前房间没风，每次向室温靠近一个常数
        if not haveWind:
            roomState["currentTemp"] += 0.1 if roomState[
                "currentTemp"] < aimTemp else -0.1
            if ((config["masterMode"] == Heating and roomState["currentTemp"] + 1 <= roomState["tarTemp"]) or (config["masterMode"] == Refrigeration and roomState["currentTemp"] - 1 >= roomState["tarTemp"])):
                config["clientMode"] = config["masterMode"]
                haveWind = True
        set_message(state_string())
        print("当前温度：%.1f 目标温度：%.1f" %
              (roomState["currentTemp"], roomState["tarTemp"]))
        time.sleep(1)
    handler["activity_run"] = True


def activity():
    handler["activity"] = threading.Thread(target=activity_thread,
                                           name='ActivityThread')
    handler["activity"].start()


def changeTarTemp(diff: int):
    min = config['temp'] if config['masterMode'] == 0 else 25
    max = 25 if config['masterMode'] == 0 else config['temp']
    aim = roomState["tarTemp"] + diff
    if min <= aim <= max:
        roomState["tarTemp"] += diff
        set_message(state_string())
        reportStateNow()


def changeMode():
    roomState["speed"] = (roomState["speed"] + 1) % 3
    set_message(state_string())
    reportStateNow()


def initClient():
    global haveWind
    haveWind = False
    roomState["tarTemp"] = config["temp"]
    if config["masterMode"] == Heating:
        roomState["currentTemp"] = WinterTemp
    elif config["masterMode"] == Refrigeration:
        roomState["currentTemp"] = SummerTemp
    reportState()
    activity()


def recvInfoDispose(data: dict):
    global init, haveWind
    delta = 25
    if data["event_id"] == 1:  # 中央空调状态反馈
        config["masterMode"] = data["data"]["mode"]
        config["temp"] = data["data"]["temp"]
        # 没有初始化进行初始化操作
        if not init:
            init = True
            initClient()
    elif data["event_id"] == 3:  # 主机送风
        if haveWind:
            roomState["cost"] = data["data"]["cost"]
            # 处理没能力送风的状态
            if data["data"]["speed"] == -1:
                if config["masterMode"] == Heating and roomState[
                        "currentTemp"] > WinterTemp:
                    roomState["currentTemp"] -= 0.1
                elif config["masterMode"] == Refrigeration and roomState[
                        "currentTemp"] < SummerTemp:
                    roomState["currentTemp"] += 0.1
            if roomState["speed"] == HighSpeed:
                delta = 15
            elif roomState["speed"] == MidSpeed:
                delta = 20
            elif roomState["speed"] == LowSpeed:
                delta = 25
            delta = 1 / delta
            if config["masterMode"] == Heating:
                if roomState["currentTemp"] + delta >= roomState["tarTemp"]:
                    # 怕用户突然调整目标温度导致需要直接停止送风
                    if abs(roomState["currentTemp"] -
                           roomState["tarTemp"]) < 0.2:
                        roomState["currentTemp"] = roomState["tarTemp"]
                    roomState["clientMode"] = StopWind
                    haveWind = False
                else:
                    roomState["currentTemp"] += delta
            else:
                if roomState["currentTemp"] - delta <= roomState["tarTemp"]:
                    if abs(roomState["currentTemp"] -
                           roomState["tarTemp"]) < 0.2:
                        roomState["currentTemp"] = roomState["tarTemp"]
                    roomState["clientMode"] = StopWind
                    haveWind = False
                else:
                    roomState["currentTemp"] -= delta
    elif data["event_id"] == 6:  # 状态汇报频率设置
        config["updateInterval"] = data["data"]["interval"]


def closeSystem():
    from .ws import ws
    ws.close()


def clearParam():
    global haveWind, init
    handler["activity_run"] = False
    handler["reportState_run"] = False
    config["masterMode"] = 0  #主机工作模式
    config["clientMode"] = StopWind  #从机当前工作模式
    haveWind = False
    init = False